% function modeFinderExcelTables
% =========================================================================
% modeFinderExcelTables creates 
% 1) OUTCELL  which has all info 
% 2) TOP MODE which stores max value, and saves it in directory 
% 3) SAVEPATH which is the name of the 
% 4) TOPCELL which has model identifiers, e.g. spec, subf, outfolder 
% =========================================================================
%
% Last Edited 8/12/2014 by TM

%% 4. Create Output TABS 
% 4.1 ESTPAR_TAB_D Output with the ordered modes 
nstrvals=size(loopStru.parMode,2);

% Initialize cell that will contain the output from the estimation as well
% as the statistics related to the estimation.
estpar_tab_d=emptycell(numpar+7,nstrvals+1);

% Row Names
estpar_tab_d(1:numpar,1)=parnames;
estpar_tab_d(numpar+2:end,1)={'logPosterior';'logLikelihood';'Number';'Iteration count';'exitflag';'minutes'};

% Column Information
estpar_tab_d(1:numpar,2:end)=num2cprec(loopStru.parMode,10);
estpar_tab_d(numpar+2,2:end)=num2cprec(loopStru.logPost(:,2)',3);
estpar_tab_d(numpar+3,2:end)=num2cprec(loopStru.logLikel(:,2)',3);
estpar_tab_d(numpar+4,2:end)=num2cprec(orderDescend',1);
estpar_tab_d(numpar+5:numpar+7, 2:end)=num2cprec(optimMat); 

% 4.2 SS_TAB_D Output with associated steady states 
% If the model computes steady-states, then we will collect the relevant
% information regarding those outputs and add them to the table.
%
% Note that this will also print out on screen.
% -------------------------------------------------------------------------
if ~isunix
    
    ssTable=writeSSTable(model.handle,model.param,...
        model.solveOptions,model.addsol);
end
% =========================================================================

% 4.3 DATAINFO_TAB Information about data used in estimation 
% -------------------------------------------------------------------------
datainfo_tab = emptycell(7, nstrvals + 1); 
datainfo_tab(1, 1:2) = {'data file', dataStru.fileName};
datainfo_tab(2, 1:2) = {'data path', dataStru.loadPath}; 
datainfo_tab(3, 1:2) = {'data range', [num2str(dataStru.start), ' to ', num2str(dataStru.finish)]}; 
if isfield(dataStru,'startest')==true
    datainfo_tab(4, 1:2) = {'data estimated', [num2str(dataStru.startest), ' to ', num2str(dataStru.finishest)]};
else
    datainfo_tab(4, 1:2) = {'data estimated', [num2str(dataStru.starest), ' to ', num2str(dataStru.finishest)]};    
end
datainfo_tab(5, 1:2) = {'demean', num2str(dataStru.demean)};
datainfo_tab(6, 1:2) = {'demean type', num2str(dataStru.demeanType)};

%% 4.4 DATASUM_TAB Names of series 
% -------------------------------------------------------------------------
datasum_tab = emptycell(nstrvals+1, size(Y, 2) + 1); 
datasum_tab{1, 1} = 'Series Names'; 
datasum_tab(1, 2:end) = Ynames; 
datasum_tab{2, 1} = 'mean';
datasum_tab(2, 2:end) = num2cprec(nanmean(Y));
datasum_tab{3, 1} = 'std dev';
datasum_tab(3, 2:end) = num2cprec(nanstd(Y));
datasum_tab = datasum_tab'; 

%% 4.5 FUNCINFO_TAB Information about solution 
% -------------------------------------------------------------------------
funcinfo_tab = emptycell(4, 2); 
funcinfo_tab(1, 1:2) = {'model', func2str(model.handle)}; 
funcinfo_tab(2, 1:2) = {'TolFun', num2str(model.solveOptions.TolFun)};
funcinfo_tab(3, 1:2) = {'MaxIter', num2str(model.solveOptions.MaxIter)};
funcinfo_tab(4, 1:2) = {'MaxFunEvals', num2str(model.solveOptions.MaxFunEvals)}; 

%% 4.6 ESTINFO_TAB Information about optimization procedure 
estinfo_tab = emptycell(5, 2); 
estinfo_tab(1, 1:2) = {'location.savePath', location.savePath};
estinfo_tab(2, 1:2) = {'routine',estimopt.funcName};
estinfo_tab(3, 1:2) = {'TolFun',num2str(estimopt.TolFun)};
estinfo_tab(4, 1:2) = {'MaxIter',num2str(estimopt.MaxIter)};
estinfo_tab(5, 1:2) = {'MaxFunEvals', num2str(estimopt.MaxFunEvals)};
% =========================================================================

%% 4.7 Write OUTCELL 
mod_est_info_tab = merge_cells(estinfo_tab, funcinfo_tab, 2); 
outcell = merge_cells(mod_est_info_tab, datainfo_tab, 2); 
outcell = merge_cells(outcell, datasum_tab, 2); 
outcell = merge_cells(outcell, estpar_tab_d, 2); 
if isunix==0 && isempty(ssTable)==false;    
    outcell = merge_cells(outcell, ssTable, 2);
end
clear mod_est_info_tab estpar_tab_d ss_tab_d datainfo_tab; 
% =========================================================================

% =========================================================================
%% 4.8 Write values of top mode to excel
cd(location.savePath)
xlsFilename=[priorStru.fileName,' ',strdate,'.xls']; 
modeCell=[parnames(:) num2cprec(model.param,15)]; 
if isunix == 0;
    xlswrite(xlsFilename,modeCell,'ModePrecision'); 
elseif isunix == 1; 
    savecell(modecell,[],location.savePath,xlsFilename);
end
clear modeCell
cd(cucd); 

%% Write top mode with STD and Hessian
%  ===================================
if exist('stdHFD','var')==0; 
    stdHFD=nan(size(loopStru.std,1),1);
end 

parTemp=nan(length(model.param),3);
parTemp(:,1)=model.param;
parTemp(posStru.param.est,2)=stdHFD;
parTemp(posStru.param.est,3)=loopStru.std(:,1);
cd(location.savePath);
if isunix==0 
    xlswrite(xlsFilename,crtcell(parTemp,parnames,{'Mode','Std FDH','Std Estimation'}),...
        'ModeDetails');
else 
    savecell(crtcell(parTemp,parnames,{'Mode','Std FDH','Std Estimation'}),[],location.savePath,...
        'ModeDetails'); 
end 
cd(cucd);

tableStru.dataMat=parTemp; 
tableStru.rowLabels=convert2tex(parnames); 
tableStru.colLabels={'Mode','Std FDH','Std Estimation'}; 
tableStru.corner={'Parameter'}; 
tableStru.tableHeader={'Mode and Hessian based stds'}; 

latexStru.printPDF=true; 
latexStru.fileName=['Estimation Report',strdate]; 
latexStru.outPath=location.savePath; 
latexStru.fileExists=false; 

cd(location.savePath);
multiPageTable(tableStru,latexStru); 
cd(cucd);


%MakeLaTeX_table(parTemp,convert2tex(parnames),{'Mode','Std FDH','Std Estimation'},...
%    {'Parameter'},{'Mode'},'ModeTable',0,location.savePath); 

%%

% save_path=cr_dir(location.savePath,'top mode'); 
% temp      = extrsubf(loadpath, cucd ); 
% tempos=strfind(temp,'\'); 
% if isempty(tempos); 
%     tempos=strfind(temp,'/'); 
% end 
% % if isunix == 0; 
% %     tempos    = findstr(temp,'\'); 
% % else
% %     tempos    = findstr(temp,'/'); 
% % end
% root=temp(tempos(1):tempos(2)-1); 
% spec=temp(tempos(2):tempos(3)-1); 
% subf=temp(tempos(3):end        ); 
% outfolder = extrsubf(save_path, loadpath);
% topcell = {'root', root;
%     'spec', spec;
%     'subf', subf;
%     'outfolder', outfolder
%     'data', dataStru.fileName};
% cd(location.savePath); 

cd(location.savePath);
if isunix==0 &&  size(outcell,2) < 250 
    xlswrite(xlsFilename,outcell,'Estimation Results');    
else
    savecell(outcell,[],location.savePath,'Est Result');
end
cd(cucd); 
disp('Added Est Results') 
% =========================================================================